﻿using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Model;
using System.Threading.Tasks;
using WMS.Models;

namespace WMS.Controllers
{
    /// <summary>
    /// 销售订单控制器
    /// </summary>
    public class OmSalesOrderController : Controller
    {
        /// <summary>
        /// 销售订单明细
        /// </summary>
        private readonly IOmSalesOrderDetailService _iosod;
        /// <summary>
        /// 销售订单
        /// </summary>
        private readonly IOmSalesOrderService _iosos;
        /// <summary>
        /// 客户
        /// </summary>
        private readonly IBiCustomerService _ibcs;
        /// <summary>
        /// 货品信息
        /// </summary>
        private readonly IBiProductService _ibps;
        private readonly IDictService _ids;
        /// <summary>
        /// 编号规则
        /// </summary>
        private readonly INumberingRuleService _inbrs;
        public OmSalesOrderController(
            IOmSalesOrderDetailService iosod,
            IOmSalesOrderService iosos,
            IBiCustomerService ibcs,
            IBiProductService ibps,
            IDictService ids,
            INumberingRuleService inbrs
            )
        {
            _iosod = iosod;
            _iosos = iosos;
            _ibcs = ibcs;
            _ibps = ibps;
            _ids = ids;
            _inbrs = inbrs;
        }

        /// <summary>
        /// 主页面
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Index()
        {
            //销售状态
            var dictStatu = await _ids.GetDictTypeAsync("sys_stockout_order_statu");
            if (dictStatu != null)
            {
                var StatuList = await _ids.GetDictDataListAsync(dictStatu.DictTypeId);
                ViewBag.TypeList = StatuList;
            }
            return View();
        }

        /// <summary>
        /// 初始数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAllAsync()
        {
            var result = _iosos.GetAllWithDetailsAsync();
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "查询失败" });
            }
        }

        /// <summary>
        /// 详细信息页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> Details(long id, string pwd)
        {
            //销售状态
            var dictStatu = await _ids.GetDictTypeAsync("sys_stockout_order_statu");
            if (dictStatu != null)
            {
                var StatuList = await _ids.GetDictDataListAsync(dictStatu.DictTypeId);
                ViewBag.TypeList = StatuList;
            }
            return View();
        }

        /// <summary>
        /// 获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Details(long id)
        {
            var result = await _iosos.GetAllWithDetailsIdAsync(id);
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "查询失败" });
            }
        }

        /// <summary>
        /// 创建页面
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Create()
        {
            //销售状态
            var dictStatu = await _ids.GetDictTypeAsync("sys_stockout_order_statu");
            if (dictStatu != null)
            {
                var StatuList = await _ids.GetDictDataListAsync(dictStatu.DictTypeId);
                ViewBag.TypeList = StatuList;
            }
            return View();
        }
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] OmSalesOrderCreateModel model)
        {
            string number = await _inbrs.GenerateAndUpdateNumberAsync(8);

            try
            {
                if (model == null)
                {
                    return Ok(new { code = 404, msg = "提交成功但无数据" });
                }
                model.SalesOrder.SalesOrderNo= number;
                // 1. 创建销售订单
                var salesOrder = model.SalesOrder;
                var result = await _iosos.CreateAsync(salesOrder);
                if (result > 0)
                {
                    // 获取新创建的销售订单ID
                    var newOrder = await _iosos.GetAllWithDetailsIdAsync(number);
                    if (newOrder == null)
                    {
                        return Ok(new { code = 500, msg = "创建订单后无法找到订单信息" });
                    }

                    long saleOrderId = newOrder[0].SalesOrderId;

                    // 2. 创建销售订单明细
                    if (model.SalesOrderDetails != null )
                    {

                        foreach (var detail in model.SalesOrderDetails)
                        {
                            detail.SalesOrderId = saleOrderId;
                           if( await _iosod.CreateAsync(detail) < 0)
                            {
                                return Ok(new { code = 500, msg = "销售订单明细创建失败" });
                            }
                        }
                    }

                    return Ok(new { code = 200, msg = "添加成功" });
                }
                else
                {
                    return Ok(new { code = 500, msg = "销售订单创建失败" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取货品库存信息（无批次版本）
        /// </summary>
        /// <param name="goodsCode">货品编码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetInventoryByGoodsCode(string goodsCode)
        {
            if (string.IsNullOrEmpty(goodsCode))
            {
                return Ok(new { code = 400, msg = "货品编码不能为空" });
            }

            try
            {
                // 调用新的无批次库存查询方法
                var result = await _iosos.GetInventoryByGoodsCode(goodsCode);
                if (result != null && result.Any())
                {
                    return Ok(new { code = 200, data = result, msg = "查询成功" });
                }
                else
                {
                    return Ok(new { code = 404, msg = "未找到该货品的库存信息" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询失败：{ex.Message}" });
            }
        }
        /// <summary>
        /// 修改页面 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Edit(int id)
        {
            return View();
        }

        /// <summary>
        /// 修改提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Edit(int id, [FromBody] OmSalesOrder data)
        {
            var result = await _iosos.UpdateAsync(data);
            if (result > 0)
            {
                return Ok(new { code = 200, msg = "更新成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "更新失败" });
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete(long id)
        {
            if (await _iosos.DeleteAsync(id) > 0)
            {
                return this.Success( "删除成功");
            }
            else
            {
                return this.Error();
            }
        }

        /// <summary>
        /// 客户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CustomerAll()
        {
            var data = await _ibcs.GetAllAsync();
            var result = data.Select(T => new
            {
                Id = T.CustomerId,
                Name = T.CustomerName,
                contactPhone=T.ContactPhone,
                contactPerson = T.ContactPerson
            }).ToList();
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "获取失败" });
            }
        }
        /// <summary>
        /// 销售订单创建模型
        /// </summary>
        public class OmSalesOrderCreateModel
        {
            public OmSalesOrder SalesOrder { get; set; }
            public List<OmSalesOrderDetail> SalesOrderDetails { get; set; }
        }
        /// <summary>
        /// 审核动作
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateAuditorComment([FromBody] Auditor date)
        {
            if (date == null)
            {
                return Ok(new { code = 400, msg = "审核数据不能为空" });
            }

            if (date.Id <= 0)
            {
                return Ok(new { code = 400, msg = "订单ID无效" });
            }

            try
            {
                var result = await _iosos.UpdateAuditorComment(date);
                if (result > 0)
                {
                    return Ok(new { code = 200, msg = "审核成功" });
                }
                else
                {
                    return Ok(new { code = 404, msg = "审核失败，订单可能不存在" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"审核异常: {ex.Message}" });
            }
        }
        /// <summary>
        /// 状态变更
        /// </summary>
        /// <param name="status">字符串类型的状态参数如0,1,2,3.....</param>
        /// <param name="id">目标订单</param>
        /// <returns></returns>
        public async Task<IActionResult> AuditorStatus(string status,long id)
        {
            if(await _iosos.AuditorStatus(status, id)>0) 
            {
                return this.Success("状态变更成功");
            }
            else
            {
                return this.Error();
            }
        }
        /// <summary>
        /// 状态变更（启用停用）
        /// </summary>
        /// <param name="status">字符串类型的状态参数如0,1,2,3.....</param>
        /// <param name="id">目标订单</param>
        /// <returns></returns>
        public async Task<IActionResult> Status(string status, long id)
        {
            if (await _iosos.Status(status, id) > 0)
            {
                return this.Success("状态变更成功");
            }
            else
            {
                return this.Error();
            }
        }
    }
}